3 * Updater for link tracking tables after a page edit.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\ScopedCallback
;
29 * Class the manages updates of *_link tables as well as similar extension-managed tables
31 * @note: LinksUpdate is managed by DeferredUpdates::execute(). Do not run this in a transaction.
33 * See docs/deferred.txt
35 class LinksUpdate
extends DataUpdate
implements EnqueueableDataUpdate
{
36 // @todo make members protected, but make sure extensions don't break
38 /** @var int Page ID of the article linked from */
41 /** @var Title Title object of the article linked from */
44 /** @var ParserOutput */
45 public $mParserOutput;
47 /** @var array Map of title strings to IDs for the links in the document */
50 /** @var array DB keys of the images used, in the array key only */
53 /** @var array Map of title strings to IDs for the template references, including broken ones */
56 /** @var array URLs of external links, array key only */
59 /** @var array Map of category names to sort keys */
62 /** @var array Map of language codes to titles */
65 /** @var array 2-D map of (prefix => DBK => 1) */
68 /** @var array Map of arbitrary name to value */
71 /** @var bool Whether to queue jobs for recursive updates */
74 /** @var Revision Revision for which this update has been triggered */
78 * @var null|array Added links if calculated.
80 private $linkInsertions = null;
83 * @var null|array Deleted links if calculated.
85 private $linkDeletions = null;
88 * @var null|array Added external links if calculated.
90 private $externalLinkInsertions = null;
93 * @var null|array Deleted external links if calculated.
95 private $externalLinkDeletions = null;
98 * @var null|array Added properties if calculated.
100 private $propertyInsertions = null;
103 * @var null|array Deleted properties if calculated.
105 private $propertyDeletions = null;
112 /** @var IDatabase */
116 * @param Title $title Title of the page we're updating
117 * @param ParserOutput $parserOutput Output from a full parse of this page
118 * @param bool $recursive Queue jobs for recursive updates?
119 * @throws MWException
121 function __construct( Title
$title, ParserOutput
$parserOutput, $recursive = true ) {
122 parent
::__construct();
124 $this->mTitle
= $title;
125 $this->mId
= $title->getArticleID( Title
::GAID_FOR_UPDATE
);
128 throw new InvalidArgumentException(
129 "The Title object yields no ID. Perhaps the page doesn't exist?"
133 $this->mParserOutput
= $parserOutput;
135 $this->mLinks
= $parserOutput->getLinks();
136 $this->mImages
= $parserOutput->getImages();
137 $this->mTemplates
= $parserOutput->getTemplates();
138 $this->mExternals
= $parserOutput->getExternalLinks();
139 $this->mCategories
= $parserOutput->getCategories();
140 $this->mProperties
= $parserOutput->getProperties();
141 $this->mInterwikis
= $parserOutput->getInterwikiLinks();
143 # Convert the format of the interlanguage links
144 # I didn't want to change it in the ParserOutput, because that array is passed all
145 # the way back to the skin, so either a skin API break would be required, or an
146 # inefficient back-conversion.
147 $ill = $parserOutput->getLanguageLinks();
148 $this->mInterlangs
= [];
149 foreach ( $ill as $link ) {
150 list( $key, $title ) = explode( ':', $link, 2 );
151 $this->mInterlangs
[$key] = $title;
154 foreach ( $this->mCategories
as &$sortkey ) {
155 # If the sortkey is longer then 255 bytes, it is truncated by DB, and then doesn't match
156 # when comparing existing vs current categories, causing T27254.
157 $sortkey = mb_strcut( $sortkey, 0, 255 );
160 $this->mRecursive
= $recursive;
162 // Avoid PHP 7.1 warning from passing $this by reference
163 $linksUpdate = $this;
164 Hooks
::run( 'LinksUpdateConstructed', [ &$linksUpdate ] );
168 * Update link tables with outgoing links from an updated article
170 * @note this is managed by DeferredUpdates::execute(). Do not run this in a transaction.
172 public function doUpdate() {
173 if ( $this->ticket
) {
174 // Make sure all links update threads see the changes of each other.
175 // This handles the case when updates have to batched into several COMMITs.
176 $scopedLock = self
::acquirePageLock( $this->getDB(), $this->mId
);
177 if ( !$scopedLock ) {
178 throw new RuntimeException( "Could not acquire lock for page ID '{$this->mId}'." );
182 // Avoid PHP 7.1 warning from passing $this by reference
183 $linksUpdate = $this;
184 Hooks
::run( 'LinksUpdate', [ &$linksUpdate ] );
185 $this->doIncrementalUpdate();
187 // Commit and release the lock (if set)
188 ScopedCallback
::consume( $scopedLock );
189 // Run post-commit hook handlers without DBO_TRX
190 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
194 // Avoid PHP 7.1 warning from passing $this by reference
195 $linksUpdate = $this;
196 Hooks
::run( 'LinksUpdateComplete', [ &$linksUpdate, $this->ticket
] );
202 * Acquire a lock for performing link table updates for a page on a DB
204 * @param IDatabase $dbw
206 * @param string $why One of (job, atomicity)
207 * @return ScopedCallback|null
210 public static function acquirePageLock( IDatabase
$dbw, $pageId, $why = 'atomicity' ) {
211 $key = "LinksUpdate:$why:pageid:$pageId";
212 $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__
, 15 );
213 if ( !$scopedLock ) {
214 $logger = LoggerFactory
::getInstance( 'SecondaryDataUpdate' );
215 $logger->info( "Could not acquire lock '{key}' for page ID '{page_id}'.", [
217 'page_id' => $pageId,
225 protected function doIncrementalUpdate() {
227 $existingPL = $this->getExistingLinks();
228 $this->linkDeletions
= $this->getLinkDeletions( $existingPL );
229 $this->linkInsertions
= $this->getLinkInsertions( $existingPL );
230 $this->incrTableUpdate( 'pagelinks', 'pl', $this->linkDeletions
, $this->linkInsertions
);
233 $existingIL = $this->getExistingImages();
234 $imageDeletes = $this->getImageDeletions( $existingIL );
235 $this->incrTableUpdate(
239 $this->getImageInsertions( $existingIL ) );
241 # Invalidate all image description pages which had links added or removed
242 $imageUpdates = $imageDeletes +
array_diff_key( $this->mImages
, $existingIL );
243 $this->invalidateImageDescriptions( $imageUpdates );
246 $existingEL = $this->getExistingExternals();
247 $this->externalLinkDeletions
= $this->getExternalDeletions( $existingEL );
248 $this->externalLinkInsertions
= $this->getExternalInsertions(
250 $this->incrTableUpdate(
253 $this->externalLinkDeletions
,
254 $this->externalLinkInsertions
);
257 $existingLL = $this->getExistingInterlangs();
258 $this->incrTableUpdate(
261 $this->getInterlangDeletions( $existingLL ),
262 $this->getInterlangInsertions( $existingLL ) );
264 # Inline interwiki links
265 $existingIW = $this->getExistingInterwikis();
266 $this->incrTableUpdate(
269 $this->getInterwikiDeletions( $existingIW ),
270 $this->getInterwikiInsertions( $existingIW ) );
273 $existingTL = $this->getExistingTemplates();
274 $this->incrTableUpdate(
277 $this->getTemplateDeletions( $existingTL ),
278 $this->getTemplateInsertions( $existingTL ) );
281 $existingCL = $this->getExistingCategories();
282 $categoryDeletes = $this->getCategoryDeletions( $existingCL );
283 $this->incrTableUpdate(
287 $this->getCategoryInsertions( $existingCL ) );
288 $categoryInserts = array_diff_assoc( $this->mCategories
, $existingCL );
289 $categoryUpdates = $categoryInserts +
$categoryDeletes;
292 $existingPP = $this->getExistingProperties();
293 $this->propertyDeletions
= $this->getPropertyDeletions( $existingPP );
294 $this->incrTableUpdate(
297 $this->propertyDeletions
,
298 $this->getPropertyInsertions( $existingPP ) );
300 # Invalidate the necessary pages
301 $this->propertyInsertions
= array_diff_assoc( $this->mProperties
, $existingPP );
302 $changed = $this->propertyDeletions +
$this->propertyInsertions
;
303 $this->invalidateProperties( $changed );
305 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
306 $this->invalidateCategories( $categoryUpdates );
307 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
309 # Refresh links of all pages including this page
310 # This will be in a separate transaction
311 if ( $this->mRecursive
) {
312 $this->queueRecursiveJobs();
315 # Update the links table freshness for this title
316 $this->updateLinksTimestamp();
320 * Queue recursive jobs for this page
322 * Which means do LinksUpdate on all pages that include the current page,
323 * using the job queue.
325 protected function queueRecursiveJobs() {
326 $action = $this->getCauseAction();
327 $agent = $this->getCauseAgent();
329 self
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks', $action, $agent );
330 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
331 // Process imagelinks in case the title is or was a redirect
332 self
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks', $action, $agent );
335 $bc = $this->mTitle
->getBacklinkCache();
336 // Get jobs for cascade-protected backlinks for a high priority queue.
337 // If meta-templates change to using a new template, the new template
338 // should be implicitly protected as soon as possible, if applicable.
339 // These jobs duplicate a subset of the above ones, but can run sooner.
340 // Which ever runs first generally no-ops the other one.
342 foreach ( $bc->getCascadeProtectedLinks() as $title ) {
343 $jobs[] = RefreshLinksJob
::newPrioritized(
346 'causeAction' => $action,
347 'causeAgent' => $agent
351 JobQueueGroup
::singleton()->push( $jobs );
355 * Queue a RefreshLinks job for any table.
357 * @param Title $title Title to do job for
358 * @param string $table Table to use (e.g. 'templatelinks')
359 * @param string $action Triggering action
360 * @param string $userName Triggering user name
362 public static function queueRecursiveJobsForTable(
363 Title
$title, $table, $action = 'unknown', $userName = 'unknown'
365 if ( $title->getBacklinkCache()->hasLinks( $table ) ) {
366 $job = new RefreshLinksJob(
371 ] + Job
::newRootJobParams( // "overall" refresh links job info
372 "refreshlinks:{$table}:{$title->getPrefixedText()}"
373 ) +
[ 'causeAction' => $action, 'causeAgent' => $userName ]
376 JobQueueGroup
::singleton()->push( $job );
383 private function invalidateCategories( $cats ) {
384 PurgeJobUtils
::invalidatePages( $this->getDB(), NS_CATEGORY
, array_keys( $cats ) );
388 * Update all the appropriate counts in the category table.
389 * @param array $added Associative array of category name => sort key
390 * @param array $deleted Associative array of category name => sort key
392 private function updateCategoryCounts( array $added, array $deleted ) {
393 global $wgUpdateRowsPerQuery;
395 if ( !$added && !$deleted ) {
399 $domainId = $this->getDB()->getDomainID();
400 $wp = WikiPage
::factory( $this->mTitle
);
401 $lbf = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
402 // T163801: try to release any row locks to reduce contention
403 $lbf->commitAndWaitForReplication( __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
405 foreach ( array_chunk( array_keys( $added ), $wgUpdateRowsPerQuery ) as $addBatch ) {
406 $wp->updateCategoryCounts( $addBatch, [], $this->mId
);
407 $lbf->commitAndWaitForReplication(
408 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
411 foreach ( array_chunk( array_keys( $deleted ), $wgUpdateRowsPerQuery ) as $deleteBatch ) {
412 $wp->updateCategoryCounts( [], $deleteBatch, $this->mId
);
413 $lbf->commitAndWaitForReplication(
414 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
419 * @param array $images
421 private function invalidateImageDescriptions( array $images ) {
422 PurgeJobUtils
::invalidatePages( $this->getDB(), NS_FILE
, array_keys( $images ) );
426 * Update a table by doing a delete query then an insert query
427 * @param string $table Table name
428 * @param string $prefix Field name prefix
429 * @param array $deletions
430 * @param array $insertions Rows to insert
432 private function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
433 $services = MediaWikiServices
::getInstance();
434 $bSize = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
435 $lbf = $services->getDBLoadBalancerFactory();
437 if ( $table === 'page_props' ) {
438 $fromField = 'pp_page';
440 $fromField = "{$prefix}_from";
443 $deleteWheres = []; // list of WHERE clause arrays for each DB delete() call
444 if ( $table === 'pagelinks' ||
$table === 'templatelinks' ||
$table === 'iwlinks' ) {
445 $baseKey = ( $table === 'iwlinks' ) ?
'iwl_prefix' : "{$prefix}_namespace";
448 $curDeletionBatch = [];
449 $deletionBatches = [];
450 foreach ( $deletions as $ns => $dbKeys ) {
451 foreach ( $dbKeys as $dbKey => $unused ) {
452 $curDeletionBatch[$ns][$dbKey] = 1;
453 if ( ++
$curBatchSize >= $bSize ) {
454 $deletionBatches[] = $curDeletionBatch;
455 $curDeletionBatch = [];
460 if ( $curDeletionBatch ) {
461 $deletionBatches[] = $curDeletionBatch;
464 foreach ( $deletionBatches as $deletionBatch ) {
466 $fromField => $this->mId
,
467 $this->getDB()->makeWhereFrom2d( $deletionBatch, $baseKey, "{$prefix}_title" )
471 if ( $table === 'langlinks' ) {
472 $toField = 'll_lang';
473 } elseif ( $table === 'page_props' ) {
474 $toField = 'pp_propname';
476 $toField = $prefix . '_to';
479 $deletionBatches = array_chunk( array_keys( $deletions ), $bSize );
480 foreach ( $deletionBatches as $deletionBatch ) {
481 $deleteWheres[] = [ $fromField => $this->mId
, $toField => $deletionBatch ];
485 $domainId = $this->getDB()->getDomainID();
487 foreach ( $deleteWheres as $deleteWhere ) {
488 $this->getDB()->delete( $table, $deleteWhere, __METHOD__
);
489 $lbf->commitAndWaitForReplication(
490 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ]
494 $insertBatches = array_chunk( $insertions, $bSize );
495 foreach ( $insertBatches as $insertBatch ) {
496 $this->getDB()->insert( $table, $insertBatch, __METHOD__
, 'IGNORE' );
497 $lbf->commitAndWaitForReplication(
498 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ]
502 if ( count( $insertions ) ) {
503 Hooks
::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
508 * Get an array of pagelinks insertions for passing to the DB
509 * Skips the titles specified by the 2-D array $existing
510 * @param array $existing
513 private function getLinkInsertions( $existing = [] ) {
515 foreach ( $this->mLinks
as $ns => $dbkeys ) {
516 $diffs = isset( $existing[$ns] )
517 ?
array_diff_key( $dbkeys, $existing[$ns] )
519 foreach ( $diffs as $dbk => $id ) {
521 'pl_from' => $this->mId
,
522 'pl_from_namespace' => $this->mTitle
->getNamespace(),
523 'pl_namespace' => $ns,
533 * Get an array of template insertions. Like getLinkInsertions()
534 * @param array $existing
537 private function getTemplateInsertions( $existing = [] ) {
539 foreach ( $this->mTemplates
as $ns => $dbkeys ) {
540 $diffs = isset( $existing[$ns] ) ?
array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
541 foreach ( $diffs as $dbk => $id ) {
543 'tl_from' => $this->mId
,
544 'tl_from_namespace' => $this->mTitle
->getNamespace(),
545 'tl_namespace' => $ns,
555 * Get an array of image insertions
556 * Skips the names specified in $existing
557 * @param array $existing
560 private function getImageInsertions( $existing = [] ) {
562 $diffs = array_diff_key( $this->mImages
, $existing );
563 foreach ( $diffs as $iname => $dummy ) {
565 'il_from' => $this->mId
,
566 'il_from_namespace' => $this->mTitle
->getNamespace(),
575 * Get an array of externallinks insertions. Skips the names specified in $existing
576 * @param array $existing
579 private function getExternalInsertions( $existing = [] ) {
581 $diffs = array_diff_key( $this->mExternals
, $existing );
582 foreach ( $diffs as $url => $dummy ) {
583 foreach ( LinkFilter
::makeIndexes( $url ) as $index ) {
585 'el_from' => $this->mId
,
587 'el_index' => $index,
588 'el_index_60' => substr( $index, 0, 60 ),
597 * Get an array of category insertions
599 * @param array $existing Mapping existing category names to sort keys. If both
600 * match a link in $this, the link will be omitted from the output
604 private function getCategoryInsertions( $existing = [] ) {
605 global $wgCategoryCollation;
606 $diffs = array_diff_assoc( $this->mCategories
, $existing );
608 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
609 $collation = Collation
::singleton();
610 foreach ( $diffs as $name => $prefix ) {
611 $nt = Title
::makeTitleSafe( NS_CATEGORY
, $name );
612 $contLang->findVariantLink( $name, $nt, true );
614 $type = MWNamespace
::getCategoryLinkType( $this->mTitle
->getNamespace() );
616 # Treat custom sortkeys as a prefix, so that if multiple
617 # things are forced to sort as '*' or something, they'll
618 # sort properly in the category rather than in page_id
620 $sortkey = $collation->getSortKey( $this->mTitle
->getCategorySortkey( $prefix ) );
623 'cl_from' => $this->mId
,
625 'cl_sortkey' => $sortkey,
626 'cl_timestamp' => $this->getDB()->timestamp(),
627 'cl_sortkey_prefix' => $prefix,
628 'cl_collation' => $wgCategoryCollation,
637 * Get an array of interlanguage link insertions
639 * @param array $existing Mapping existing language codes to titles
643 private function getInterlangInsertions( $existing = [] ) {
644 $diffs = array_diff_assoc( $this->mInterlangs
, $existing );
646 foreach ( $diffs as $lang => $title ) {
648 'll_from' => $this->mId
,
658 * Get an array of page property insertions
659 * @param array $existing
662 function getPropertyInsertions( $existing = [] ) {
663 $diffs = array_diff_assoc( $this->mProperties
, $existing );
666 foreach ( array_keys( $diffs ) as $name ) {
667 $arr[] = $this->getPagePropRowData( $name );
674 * Returns an associative array to be used for inserting a row into
675 * the page_props table. Besides the given property name, this will
676 * include the page id from $this->mId and any property value from
677 * $this->mProperties.
679 * The array returned will include the pp_sortkey field if this
680 * is present in the database (as indicated by $wgPagePropsHaveSortkey).
681 * The sortkey value is currently determined by getPropertySortKeyValue().
683 * @note this assumes that $this->mProperties[$prop] is defined.
685 * @param string $prop The name of the property.
689 private function getPagePropRowData( $prop ) {
690 global $wgPagePropsHaveSortkey;
692 $value = $this->mProperties
[$prop];
695 'pp_page' => $this->mId
,
696 'pp_propname' => $prop,
697 'pp_value' => $value,
700 if ( $wgPagePropsHaveSortkey ) {
701 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
708 * Determines the sort key for the given property value.
709 * This will return $value if it is a float or int,
710 * 1 or resp. 0 if it is a bool, and null otherwise.
712 * @note In the future, we may allow the sortkey to be specified explicitly
713 * in ParserOutput::setProperty.
715 * @param mixed $value
719 private function getPropertySortKeyValue( $value ) {
720 if ( is_int( $value ) ||
is_float( $value ) ||
is_bool( $value ) ) {
721 return floatval( $value );
728 * Get an array of interwiki insertions for passing to the DB
729 * Skips the titles specified by the 2-D array $existing
730 * @param array $existing
733 private function getInterwikiInsertions( $existing = [] ) {
735 foreach ( $this->mInterwikis
as $prefix => $dbkeys ) {
736 $diffs = isset( $existing[$prefix] )
737 ?
array_diff_key( $dbkeys, $existing[$prefix] )
740 foreach ( $diffs as $dbk => $id ) {
742 'iwl_from' => $this->mId
,
743 'iwl_prefix' => $prefix,
753 * Given an array of existing links, returns those links which are not in $this
754 * and thus should be deleted.
755 * @param array $existing
758 private function getLinkDeletions( $existing ) {
760 foreach ( $existing as $ns => $dbkeys ) {
761 if ( isset( $this->mLinks
[$ns] ) ) {
762 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks
[$ns] );
764 $del[$ns] = $existing[$ns];
772 * Given an array of existing templates, returns those templates which are not in $this
773 * and thus should be deleted.
774 * @param array $existing
777 private function getTemplateDeletions( $existing ) {
779 foreach ( $existing as $ns => $dbkeys ) {
780 if ( isset( $this->mTemplates
[$ns] ) ) {
781 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates
[$ns] );
783 $del[$ns] = $existing[$ns];
791 * Given an array of existing images, returns those images which are not in $this
792 * and thus should be deleted.
793 * @param array $existing
796 private function getImageDeletions( $existing ) {
797 return array_diff_key( $existing, $this->mImages
);
801 * Given an array of existing external links, returns those links which are not
802 * in $this and thus should be deleted.
803 * @param array $existing
806 private function getExternalDeletions( $existing ) {
807 return array_diff_key( $existing, $this->mExternals
);
811 * Given an array of existing categories, returns those categories which are not in $this
812 * and thus should be deleted.
813 * @param array $existing
816 private function getCategoryDeletions( $existing ) {
817 return array_diff_assoc( $existing, $this->mCategories
);
821 * Given an array of existing interlanguage links, returns those links which are not
822 * in $this and thus should be deleted.
823 * @param array $existing
826 private function getInterlangDeletions( $existing ) {
827 return array_diff_assoc( $existing, $this->mInterlangs
);
831 * Get array of properties which should be deleted.
832 * @param array $existing
835 function getPropertyDeletions( $existing ) {
836 return array_diff_assoc( $existing, $this->mProperties
);
840 * Given an array of existing interwiki links, returns those links which are not in $this
841 * and thus should be deleted.
842 * @param array $existing
845 private function getInterwikiDeletions( $existing ) {
847 foreach ( $existing as $prefix => $dbkeys ) {
848 if ( isset( $this->mInterwikis
[$prefix] ) ) {
849 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis
[$prefix] );
851 $del[$prefix] = $existing[$prefix];
859 * Get an array of existing links, as a 2-D array
863 private function getExistingLinks() {
864 $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
865 [ 'pl_from' => $this->mId
], __METHOD__
);
867 foreach ( $res as $row ) {
868 if ( !isset( $arr[$row->pl_namespace
] ) ) {
869 $arr[$row->pl_namespace
] = [];
871 $arr[$row->pl_namespace
][$row->pl_title
] = 1;
878 * Get an array of existing templates, as a 2-D array
882 private function getExistingTemplates() {
883 $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
884 [ 'tl_from' => $this->mId
], __METHOD__
);
886 foreach ( $res as $row ) {
887 if ( !isset( $arr[$row->tl_namespace
] ) ) {
888 $arr[$row->tl_namespace
] = [];
890 $arr[$row->tl_namespace
][$row->tl_title
] = 1;
897 * Get an array of existing images, image names in the keys
901 private function getExistingImages() {
902 $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
903 [ 'il_from' => $this->mId
], __METHOD__
);
905 foreach ( $res as $row ) {
906 $arr[$row->il_to
] = 1;
913 * Get an array of existing external links, URLs in the keys
917 private function getExistingExternals() {
918 $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
919 [ 'el_from' => $this->mId
], __METHOD__
);
921 foreach ( $res as $row ) {
922 $arr[$row->el_to
] = 1;
929 * Get an array of existing categories, with the name in the key and sort key in the value.
933 private function getExistingCategories() {
934 $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
935 [ 'cl_from' => $this->mId
], __METHOD__
);
937 foreach ( $res as $row ) {
938 $arr[$row->cl_to
] = $row->cl_sortkey_prefix
;
945 * Get an array of existing interlanguage links, with the language code in the key and the
946 * title in the value.
950 private function getExistingInterlangs() {
951 $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
952 [ 'll_from' => $this->mId
], __METHOD__
);
954 foreach ( $res as $row ) {
955 $arr[$row->ll_lang
] = $row->ll_title
;
962 * Get an array of existing inline interwiki links, as a 2-D array
963 * @return array (prefix => array(dbkey => 1))
965 private function getExistingInterwikis() {
966 $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
967 [ 'iwl_from' => $this->mId
], __METHOD__
);
969 foreach ( $res as $row ) {
970 if ( !isset( $arr[$row->iwl_prefix
] ) ) {
971 $arr[$row->iwl_prefix
] = [];
973 $arr[$row->iwl_prefix
][$row->iwl_title
] = 1;
980 * Get an array of existing categories, with the name in the key and sort key in the value.
982 * @return array Array of property names and values
984 private function getExistingProperties() {
985 $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
986 [ 'pp_page' => $this->mId
], __METHOD__
);
988 foreach ( $res as $row ) {
989 $arr[$row->pp_propname
] = $row->pp_value
;
996 * Return the title object of the page being updated
999 public function getTitle() {
1000 return $this->mTitle
;
1004 * Returns parser output
1006 * @return ParserOutput
1008 public function getParserOutput() {
1009 return $this->mParserOutput
;
1013 * Return the list of images used as generated by the parser
1016 public function getImages() {
1017 return $this->mImages
;
1021 * Set the revision corresponding to this LinksUpdate
1025 * @param Revision $revision
1027 public function setRevision( Revision
$revision ) {
1028 $this->mRevision
= $revision;
1033 * @return null|Revision
1035 public function getRevision() {
1036 return $this->mRevision
;
1040 * Set the User who triggered this LinksUpdate
1045 public function setTriggeringUser( User
$user ) {
1046 $this->user
= $user;
1053 public function getTriggeringUser() {
1058 * Invalidate any necessary link lists related to page property changes
1059 * @param array $changed
1061 private function invalidateProperties( $changed ) {
1062 global $wgPagePropLinkInvalidations;
1064 foreach ( $changed as $name => $value ) {
1065 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1066 $inv = $wgPagePropLinkInvalidations[$name];
1067 if ( !is_array( $inv ) ) {
1070 foreach ( $inv as $table ) {
1071 DeferredUpdates
::addUpdate(
1072 new HTMLCacheUpdate( $this->mTitle
, $table, 'page-props' )
1080 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
1082 * @return null|array Array of Titles
1084 public function getAddedLinks() {
1085 if ( $this->linkInsertions
=== null ) {
1089 foreach ( $this->linkInsertions
as $insertion ) {
1090 $result[] = Title
::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1097 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
1099 * @return null|array Array of Titles
1101 public function getRemovedLinks() {
1102 if ( $this->linkDeletions
=== null ) {
1106 foreach ( $this->linkDeletions
as $ns => $titles ) {
1107 foreach ( $titles as $title => $unused ) {
1108 $result[] = Title
::makeTitle( $ns, $title );
1116 * Fetch external links added by this LinksUpdate. Only available after
1117 * the update is complete.
1119 * @return null|array Array of Strings
1121 public function getAddedExternalLinks() {
1122 if ( $this->externalLinkInsertions
=== null ) {
1126 foreach ( $this->externalLinkInsertions
as $key => $value ) {
1127 $result[] = $value['el_to'];
1133 * Fetch external links removed by this LinksUpdate. Only available after
1134 * the update is complete.
1136 * @return null|array Array of Strings
1138 public function getRemovedExternalLinks() {
1139 if ( $this->externalLinkDeletions
=== null ) {
1142 return array_keys( $this->externalLinkDeletions
);
1146 * Fetch page properties added by this LinksUpdate.
1147 * Only available after the update is complete.
1149 * @return null|array
1151 public function getAddedProperties() {
1152 return $this->propertyInsertions
;
1156 * Fetch page properties removed by this LinksUpdate.
1157 * Only available after the update is complete.
1159 * @return null|array
1161 public function getRemovedProperties() {
1162 return $this->propertyDeletions
;
1166 * Update links table freshness
1168 private function updateLinksTimestamp() {
1170 // The link updates made here only reflect the freshness of the parser output
1171 $timestamp = $this->mParserOutput
->getCacheTime();
1172 $this->getDB()->update( 'page',
1173 [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1174 [ 'page_id' => $this->mId
],
1183 private function getDB() {
1185 $this->db
= wfGetDB( DB_MASTER
);
1191 public function getAsJobSpecification() {
1192 if ( $this->user
) {
1194 'userId' => $this->user
->getId(),
1195 'userName' => $this->user
->getName(),
1201 if ( $this->mRevision
) {
1202 $triggeringRevisionId = $this->mRevision
->getId();
1204 $triggeringRevisionId = false;
1208 'wiki' => WikiMap
::getWikiIdFromDbDomain( $this->getDB()->getDomainID() ),
1209 'job' => new JobSpecification(
1210 'refreshLinksPrioritized',
1212 // Reuse the parser cache if it was saved
1213 'rootJobTimestamp' => $this->mParserOutput
->getCacheTime(),
1214 'useRecursiveLinksUpdate' => $this->mRecursive
,
1215 'triggeringUser' => $userInfo,
1216 'triggeringRevisionId' => $triggeringRevisionId,
1217 'causeAction' => $this->getCauseAction(),
1218 'causeAgent' => $this->getCauseAgent()
1220 [ 'removeDuplicates' => true ],